var classes = {
	imgContainer : 'image-holder'
};

// images after a battle
var sortedImages = [];

// images before a battle
var battleImages = [];

// Moves elemA before elemB in array. If elemA was in the array
// previously, it is removed. The behavior is undefined unless
// elemB is in 'array'
var moveBefore = function(array, elemA, elemB) {
	for (var i=0; i < array.length; i++) {
		var current = array[i];
		if (current === elemA) {
			array.splice(i--, 1);
		}
		else if (current === elemB) {
			array.splice(i++, 0, elemA);
		}
	}
}

// rearranges the images in the 'current battle' pane
// according to the new ordering created by the last
// preference click
function updateBattleImages() {
	for (var i = 0; i < sortedImages.length; i++) {
		battleImages[i].setAttribute('src', sortedImages[i].url);
		battleImages[i].className = 'thumb';
	}
	
	for (var i = sortedImages.length; i < battleImages.length; i++) {
		battleImages[i].className = 'empty';
	}
}

// chooses the next two images to battle based upon the winner and loser
// of the prior battle and the current battle stage
var clickHandler = function(event) {
	var aHolder = document.getElementById('a'); 
	var a = aHolder.children[0];
	var aText = aHolder.children[1];
	
	var bHolder = document.getElementById('b');
	var b = bHolder.children[0];
	var bText = bHolder.children[1];
	
	var winner = event.target;
	var loser = winner === a ? b : a;
	
	var winnerIndex = sortedImages.indexOf(winner.image);
	var imgA, imgB;
	
	if (winnerIndex >= 0) { // all images battled at least once
		moveBefore(sortedImages, 
				   winner.image, 
				   loser.image);
				   
	    if (winnerIndex > 1) { // consolation fight over, fight winners
	    	imgA = sortedImages[0];
			a.setAttribute('src', imgA.url);
			a.image = imgA;
			aText.innerText = imgA.title;
			
			imgB = sortedImages[1];
			b.setAttribute('src', imgB.url);
			b.image = imgB;
			bText.innerText = imgB.title;
		}
	    else { // battle over, send talkback
			console.log('Sorted! ', sortedImages);
			window.location = 'battle.jsp?img1=' + sortedImages[0].url
							  + '&img2=' + sortedImages[1].url
							  + '&img3=' + sortedImages[2].url
							  + '&img4=' + sortedImages[3].url;
		}
	}
	else { // not all images have battled yet
		sortedImages.unshift(winner.image);
		sortedImages.push(loser.image);
		
		if (imgList.length > 0) { // first two done, fight the next two
			imgA = imgList.pop();
			a.setAttribute('src', imgA.url);
			a.image = imgA;
			aText.innerText = imgA.title;
			
			imgB = imgList.pop();
			b.setAttribute('src', imgB.url);
			b.image = imgB;
			bText.innerText = imgB.title;
		}
		else { // all four finished their first fight, battle the losers
			imgA = sortedImages[2];
			a.setAttribute('src', imgA.url);
			a.image = imgA;
			aText.innerText = imgA.title; 
			
			imgB = sortedImages[3];
			b.setAttribute('src', imgB.url);
			b.image = imgB;
			bText.innerText = imgB.title;
		}
	}
	
	updateBattleImages();
};

// if a thumbnail is clicked, open it in the browser
function viewImageOnClick(event) {
	if (event.target.className !== 'thumb') {
		return;
	}
	
	var url = event.target.getAttribute('src');
	if (url !== "") {
		var dropdown = document.getElementById('category-select');
		if (dropdown.value !== 'all') {
			window.location = 'browser.jsp?url=' + url + '&tag=' + dropdown.value;
		}
		else {
			window.location = 'browser.jsp?url=' + url;
		}
	}
}

// item selected from the combo box, update the ladder
function changeLadder(event) {
	var table = document.getElementById('top-table');
	var newHTML = '			\
		<tr>				\
			<th>Img</th>	\
			<th>Rating</th>	\
			<th>Title</th>	\
		</tr>				\
	';
		
	var list;
	switch (event.target.value) {
	case 'cat':
		list = catList;
		break;
	case 'dog':
		list = dogList;
		break;
	case 'bird':
		list = birdList;
		break;
	case 'human':
		list = humanList;
		break;
	case 'pets':
		list = petsList;
		break;
	case 'wildlife':
		list = wildlifeList;
		break;
	default:
		list = allList;
		break;
	}
	
	for (var i=0; i < list.length; i++) {
		var item = list[i];
		newHTML += '												\
			<tr>													\
				<td>												\
					<div class="image-holder">						\
						<img class="thumb" src="' + item.url + '">	\
					</div>											\
				</td>												\
				<td><div>' + item.rating + '</div></td>				\
				<td><div>' + item.title  + '</div></td>				\
			</tr>													\
		';
	}
	table.innerHTML = newHTML;
}

window.onload = function(event) {
	var aHolder = document.getElementById('a');
	var a = aHolder.children[0];
	
	var imgA = imgList.shift();
	a.setAttribute('src', imgA.url);
	a.image = imgA;
	a.addEventListener('click', clickHandler);
	
	var aText = aHolder.children[1];
	aText.innerText = imgA.title;
	
	var bHolder = document.getElementById('b');
	var b = bHolder.children[0];
	
	var imgB = imgList.shift();
	b.setAttribute('src', imgB.url);
	b.image = imgB;
	b.addEventListener('click', clickHandler);
	
	var bText = bHolder.children[1];
	bText.innerText = imgB.title;
	
	battleImages = [
        document.getElementById('first'),
        document.getElementById('second'),
        document.getElementById('third'),
        document.getElementById('fourth')
    ];
	
	document.addEventListener('click', viewImageOnClick);
	
	var selecter = document.getElementById('category-select');
	selecter.onchange = changeLadder;
	changeLadder({target : selecter});
}